﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.Linq;
using BLL;
using Library;


public partial class FinaceRecordManager : System.Web.UI.Page
{
    private FinaceRecordBll bll = new FinaceRecordBll();

    /// <summary>
    ///  收支类型
    /// </summary>
    protected int TreeSelectValue
    {
        get
        {
            if (hdnSelectValue.Value == String.Empty)
            {
                return -1;
            }
            else
            {
                return int.Parse(hdnSelectValue.Value);
            }
        }
    }

    /// <summary>
    ///  ajax请求类型
    /// </summary>
    protected string AjaxType
    {
        get
        {
            return Request.QueryString["AjaxType"];
        }
    }

    /// <summary>
    /// ajax请求关键信息
    /// </summary>
    protected string AjaxKey
    {
        get
        {
            return Request.QueryString["Key"] != null ? Request.QueryString["Key"].Trim() : String.Empty ;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if ( this.AjaxType != null)
        {
            this.BuildAjaxResponse();
            Response.End();
        }

        if (!Page.IsPostBack)
        {
            this.InitUI();
        }
    }

    private void BuildAjaxResponse()
    {
        //获取服务器时间
        DateTime startTime = new DateTime();
        DateTime endTime = new DateTime();

        switch (this.AjaxKey)
        {
            case "lastDay"://昨天
                DateHelper.GetDateStartAndEnd(DateTime.Now, DateType.Day, ref startTime, ref endTime, 1);
                break;
            case "lastWeek"://最近一周
                DateHelper.GetDateStartAndEnd(DateTime.Now, DateType.Week, ref startTime, ref endTime, 1);
                break;
            case "currentMonth"://本月
                DateHelper.GetDateStartAndEnd(DateTime.Now, DateType.Month, ref startTime, ref endTime, 0);
                break;
            case "lastMonth"://上一月
                DateHelper.GetDateStartAndEnd(DateTime.Now, DateType.Month, ref startTime, ref endTime, 1);
                break;
            case "all"://显示所有记录
                break;
        }

        string strStartTime = startTime.ToYYYYMMDD();
        string strEndTime = endTime.ToYYYYMMDD();

        if( this.AjaxKey =="all")
        {
            strStartTime = String.Empty;
            strEndTime = String.Empty;
        }

        string responseJon = "{StartTime:'@@startTime',EndTime:'@@endTime'}";
        responseJon = responseJon.Replace("@@startTime", strStartTime);
        responseJon = responseJon.Replace("@@endTime", strEndTime);

        Response.Write(responseJon);
    }

    private void InitUI()
    {
        this.txtFinaceTimeStart.Text = DateTime.Now.AddDays(-9).ToYYYYMMDD();
        this.txtFinaceTimeEnd.Text = DateTime.Now.ToYYYYMMDD();

        this.BindGrid();

        ScriptManager.RegisterStartupScript(this, this.GetType(), "hide", "$('#tblQuery').hide();", true);
    }

    private QueryFinaceRecordPar InitQueryPar()
    {
        int parentPayTypeID = this.TreeSelectValue;
        //异步查询
        this.txtFinaceType.Text = Request["txtFinaceType"];

        DateTime finaceTimeStart = new DateTime(2000, 1, 1);
        if (this.txtFinaceTimeStart.Text.Trim() != String.Empty)
        {
            finaceTimeStart = DateTime.Parse(this.txtFinaceTimeStart.Text);
        }
        DateTime finaceTimeEnd = new DateTime(9999, 1, 1);
        if (this.txtFinaceTimeEnd.Text.Trim() != String.Empty)
        {
            finaceTimeEnd = DateTime.Parse(this.txtFinaceTimeEnd.Text);
        }

        decimal amount = 0;
        int amountOperator = 1;//1表示大于
        if (this.txtAmount.Text.Trim() != string.Empty)
        {
            amount = decimal.Parse(this.txtAmount.Text);
            amountOperator = int.Parse(this.dropAmountOperator.SelectedValue);
        }

        QueryFinaceRecordPar entity = new QueryFinaceRecordPar();
        entity.ParentPayTypeID = parentPayTypeID;
        entity.MemberID = HttpMemberInfo.MemerID;
        entity.FinaceTimeStart = finaceTimeStart;
        entity.FinaceTimeEnd = finaceTimeEnd;
        entity.Amount = amount;
        entity.AmountOperator = amountOperator;
        entity.Detail = this.txtDetail.Text;
        entity.PageSize = this.gdvShow.PageSize;
        entity.PageIndex = this.gdvShow.PageIndex;

        return entity;
    }

    private void BindGrid()
    {
       QueryFinaceRecordPar entity = this.InitQueryPar();
       int rowCount = 0;
       DataTable dt = bll.SelectFinaceRecord(entity,out rowCount);

       this.AspNetPager1.PageSize = this.gdvShow.PageSize;
       this.AspNetPager1.CurrentPageIndex = this.gdvShow.PageIndex;
       this.AspNetPager1.RecordCount = rowCount;

       this.gdvShow.DataKeyNames = new string[] { "FinaceRecordID" };
       this.gdvShow.DataSource = dt;
       this.gdvShow.DataBind();


       FinaceTypeStatus type = FinaceTypeStatus.All;
       if (this.TreeSelectValue != -1)
       {
           FinaceTypeBll typeBl = new FinaceTypeBll();
           bool isPayOut = typeBl.IsPayOutFinaceType(this.TreeSelectValue);
           type = isPayOut ? FinaceTypeStatus.PayOut : FinaceTypeStatus.Income;
       }

       if (type == FinaceTypeStatus.PayOut)
       {   //隐藏收入金额列
           this.gdvShow.Columns[3].Visible = false;
           this.gdvShow.Columns[2].Visible = true;
       }
       else if( type == FinaceTypeStatus.Income)
       {
           //隐藏支出金额列
           this.gdvShow.Columns[2].Visible = false;
           this.gdvShow.Columns[3].Visible = true;
       }
       else
       {
           this.gdvShow.Columns[2].Visible = true;
           this.gdvShow.Columns[3].Visible = true;
        }

       this.AnalyzeFinaceRecord(dt.Rows.Count, entity, type);
    }

    private void AnalyzeFinaceRecord(int rowCount, QueryFinaceRecordPar entity, FinaceTypeStatus type)
    {
        //隐藏统计项
        if (rowCount == 0)
        {
            this.ulAnalyzeFinaceRecord.Visible = false;
        }
        else
        {
            this.ulAnalyzeFinaceRecord.Visible = true;

            AnalyzeFinaceRecordResult result = bll.AnalyzeFinaceRecord(entity, type.GetHashCode());

            if (result.Days != -1)
            {
                this.lblDayCount.Text = result.Days.ToString();
            }
            else
            {
                this.lblDayCount.Text = "所有记录";
            }

            this.liDayInCome.Visible = false;
            this.liInComeAmount.Visible = false;
            this.liDayPayOut.Visible = false;
            this.liPayOutSum.Visible = false;

            this.lblDayPayOut.Text = MoneyToString(result.payOutdayAmount);
            this.lblPayOutSum.Text = MoneyToString(result.payoutAmount);
            this.lblDayInCome.Text = MoneyToString(result.incomeDayAmount);
            this.lblInComeAmount.Text = MoneyToString(result.incomeAmount);

            if (type == FinaceTypeStatus.PayOut)
            {
             
                this.liDayPayOut.Visible = true;
                this.liPayOutSum.Visible = true;
            }
            else if (type == FinaceTypeStatus.Income)
            {
          
                this.liDayInCome.Visible = true;
                this.liInComeAmount.Visible = true;
            }
            else
            {
                this.liDayInCome.Visible = true;
                this.liInComeAmount.Visible = true;
                this.liDayPayOut.Visible = true;
                this.liPayOutSum.Visible = true;
            }

        }
    }

    private string MoneyToString(decimal? number)
    {
        if (number == null)
        {
            return "￥0";
        }

        var temp = (decimal)number;

        return temp.ToString("C2");
    }

    
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        this.BindGrid();
    }

    protected void gdvShow_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int recordID = Convert.ToInt32(this.gdvShow.DataKeys[e.RowIndex].Value);
        bll.DelFinaceRecord(recordID);


        this.BindGrid();
    }

    protected void gdvShow_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex >= 0)
        {
            DataRowView data = e.Row.DataItem as DataRowView;
            Label lblPayoutAmount = e.Row.FindControl("lblPayoutAmount") as Label;
            Label lblIncomeAmount = e.Row.FindControl("lblIncomeAmount") as Label;

            if (Convert.ToBoolean(data["IsPayOut"]))
            {
                lblPayoutAmount.Text = data["Amount"].ToString();
            }
            else
            {
                lblIncomeAmount.Text = data["Amount"].ToString();
            }
        }
    }

    protected void btnRef_Click(object sender, EventArgs e)
    {
        this.BindGrid();
    }

    protected void gdvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        
    }

    protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        this.gdvShow.PageIndex = e.NewPageIndex;
        this.BindGrid();
    }

    public enum FinaceTypeStatus
    {
        All = -1,
        PayOut = 2,
        Income = 3
    }

}
